<?php
namespace ff\network;

use ff;
use ff\base\Exception;

class Response
{

    private $request;
    public $outVars = [];

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function __invoke($outVars)
    {
        $this->outVars = $outVars;
        $this->output($outVars);
    }

    public function varsCodeParse()
    {
        if (!isset($this->outVars['code'])) {
            return;
        }
        $codeErrors = require SYSTEM_ROOT_PATH . '/data/error.php';

        $code = $this->outVars['code'];

        if (isset($codeErrors['code'][$code])) {
            $this->outVars['msg'] = $codeErrors['code'][$code];
        }
    }

    public function outFormat()
    {
        $format = $this->router->_FORMAT ?: key(ff::$config['response']);
        if (isset(ff::$config['response'][$format])) {
            $format = ff::createObject(ff::$config['response'][$format]);
            return $format($this->outVars);
        } else {
            throw new Exception("Response Format error");
        }
    }
    public function varsTime()
    {
        $this->outVars['request_dateline'] = SYSTEM_BEGIN_TIME;
        $this->outVars['response_dateline'] = microtime(true);
    }

    public function varsRequest()
    {
        $this->outVars['request_params'] = $this->router->request->vars;
    }

    public function header($method = null)
    {
        @header("Expires: -1");
        @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", false);
        @header("Pragma: no-cache");
        @header('Access-Control-Allow-Credentials:true');
        @header("Access-Control-Allow-Headers:x-requested-with,content-type");

        if (isset($this->router->request->vars['domain'])) {
            if (preg_match('/^http:\/\//is', $this->router->request->vars['domain'])) {
                $domain = $this->router->request->vars['domain'];
            } else {
                $domain = 'http://' . $this->router->request->vars['domain'];
            }
            @header('Access-Control-Allow-Origin:' . $domain);
        } else {
            @header('Access-Control-Allow-Origin:*');
        }
    }

    private function output()
    {
        $this->header();
        $this->varsCodeParse();
        $this->varsRequest();

        $this->varsTime();
        $output = $this->outFormat();
        echo $output;
    }

}
